package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室的服务器
 *
 * 利用多线程实现多个客户端可以同时 连接服务端;
 *
 * 功能1:实现将消息群发给所有客户端
 * 功能2:广播消息
 * 1)将广播消息提取成一个方法,并取名为sengMessage
 *
 *
 */
public class Server5 {
    /**
     * java.net.ServerSocket
     * 运行在服务端的ServerSocket的主要任务
     * 1.向服务端申请服务端口.客户端就是通过该端口与服务器建立连接
     * 2.监听服务端口,一旦一个客户端连接了机会立即创建一个Socket实例与之交互
     */
    private ServerSocket serverSocket;
    private List<PrintWriter> allOut = new ArrayList<>();
    public Server5(){
        try{
            //如果端口被其他程序占用了,则会发生异常:
            //解决办法:1.更换端口号2.杀死占用该端口的进程
            System.out.println("正在启动服务端");
            serverSocket=new ServerSocket(8088);
            System.out.println("服务器启动完毕");
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public void start(){
        /*
        ServerSocket提供了重要方法:Socket accept();
        用于接受客户端的连接,并返回一个Socket实例与连接的客户端交互
        该方法是一个阻塞方法,调用后程序会"卡住",直到一个客户端链接为止
         */
        try {
            while(true) {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接上了");
                //启动一个线程
                Runnable r = new ClientHandler(socket);
                Thread t = new Thread(r);
                t.start();
            }
            /*
            InputStream in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
            BufferedReader bw = new BufferedReader(isr);
            String message;
            while ((message = bw.readLine()) != null) {
                System.out.println("客户说:"+message);
            }
             */

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        Server5 server = new Server5();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录该客户端的IP地址

        public ClientHandler(Socket socket){
            this.socket=socket;
            //通过socket获取远端计算机的IP地址的字符串格式
            host = socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw =null;//提高pw的作用域,以便finally中可以将其从allOut集合中删除
            try {//Ctrl+Alt+T
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                //
                synchronized(allOut){
                    allOut.add(pw);
                }
                sendMessage(host+"上线了,当前在线人数:"+allOut.size());

                String message;
                while ((message = br.readLine()) != null) {
                    //读取到客户端消息广播是改为调用sendMessage方法
                    sendMessage(host+"说:"+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //广播该客户端下线了,几个同步锁,防止多个用户同时下线出现并发问题;
                synchronized (allOut){
                    allOut.remove(pw);
                }
                sendMessage(host+"下线了,当前在线人数:"+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        /**
         *
         *
         */
        private void sendMessage(String message){
            System.out.println(message);
            //遍历allOut集合,给所有客户端发送这个消息
            //新循环就是迭代器,迭代器要求遍历过程不能用集合方法增删元素,所以需要和上面的增删互斥;
            synchronized (allOut){
                for(PrintWriter l: allOut){
                    l.println(message);
                }
            }
        }

    }
}
